import re

from rest_framework import serializers
from myapp.models import *
from rest_framework.exceptions import ValidationError


# 邮件信息
class MailSer(serializers.ModelSerializer):
    class Meta:
        model = Mail
        exclude = ['create_time', 'update_time', "is_delete"]
        read_only_fields = ['id']

    def validate(self, attrs):
        user = attrs.get("user")
        email = attrs.get("recipients_url")

        if email != None:
            if not re.findall(r'^[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+){0,4}@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+){0,4}$', email):
                raise ValidationError(f'{email} 邮箱格式不正确！')

        if user != None:
            user_list = UserModel.objects.filter(is_delete=0).values("id")
            user_list = [i.get("id") for i in user_list]
            if user.id not in user_list:
                raise ValidationError(f"{user} 该用户不存在！")

        return attrs